<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :before-close="closeDialog"
    class
    :close-on-click-modal="false"
    :append-to-body="true"
  >
    <!-- <div class="title-gra plr30">
      <div class="grab gra-r">
        <span class="grab gra-l"></span>
      </div>
    </div> -->
    <div v-loading="loading">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="用户ID：" prop="account">
          <el-input v-model="ruleForm.account" :disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名：" prop="userName">
          <el-input v-model="ruleForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="身份证号：" prop="idCardNumber">
          <el-input v-model="ruleForm.idCardNumber"></el-input>
        </el-form-item>
        <el-form-item :label="staffNo" style="padding-left:10px;" label-width="90px">
          <el-input v-model="ruleForm.policeId"></el-input>
        </el-form-item>
        <el-form-item label="单位名称：" prop="companyName">
          <el-input v-model="ruleForm.companyName"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password" :required="!disabled" v-if="!disabled">
          <el-input  v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password" :required="!disabled" v-if="disabled"  style="padding-left:10px;" label-width="90px">
          <el-input  v-model="ruleForm.password"></el-input>
        </el-form-item>
      </el-form>
      <div class="mr-btn">
        <el-button class="def-btn-sty" @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import {
  addUserInfo,
  updateUser,
  addCloakUserRole,
  deleteUserInfo,
  getUserList
} from "@/api/userApi.js";
export default {
  data() {
    var validateAccount = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("用户ID不能为空"));
      } else if (!/^[a-z][a-z0-9]{3,17}$/.test(value)) {
        callback(new Error("小写字母开头，允许输入4-18位的小写字母或数字"));
      } else {
        callback();
      }
    };
    var validateIdCardNumber = (rule, value, callback) => {
      if (value && !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X)$)/.test(value)) {
        callback(new Error("身份证号码格式不正确"));
      } else {
        callback();
      }
    };
    var validateuserName = (rule, value, callback) => {
      if (value && !/^[a-zA-Z\u4E00-\u9FA5.]{0,20}$/.test(value)) {
        callback(new Error("允许输入20位的中文，英文字母或者."));
      } else {
        callback();
      }
    };
    var validatecompanyName = (rule, value, callback) => {
      if (value && !/^[a-zA-Z0-9\u4E00-\u9FA5]{0,100}$/.test(value)) {
        callback(new Error("允许输入100位的中文，英文字母或者."));
      } else {
        callback();
      }
    };
    var validatePassword = (rule, value, callback) => {
      if (!this.disabled) {
        if (value == "") {
          callback(new Error("密码不能为空"));
        } else if (
          value &&
          !/^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[_@.#!%$])[\da-zA-Z_@.#!%$]{8,16}$/.test(
            value
          )
        ) {
          callback(
            new Error("由8-16位的大写字母、小写字母、数字和特殊字符_@.#!%$组成")
          );
        } else {
          callback();
        }
      } else {
        if (
          value &&
          !/^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[_@.#!%$])[\da-zA-Z_@.#!%$]{8,16}$/.test(
            value
          )
        ) {
          callback(
            new Error("由8-16位的大写字母、小写字母、数字和特殊字符_@.#!%$组成")
          );
        } else {
          callback();
        }
      }
    };
    return {
      dialogVisible: false,
      disabled: false,
      userId: "",
      title: "新增用户",
      loading: false,
      ruleForm: {
        account: "",
        userName: "",
        idCardNumber: "",
        policeId: "",
        companyName: "",
        password: "",
        isKpi: false
      },
      rules: {
        account: [
          { required: true, message: "用户ID不能为空", trigger: "blur" },
          { validator: validateAccount, trigger: "blur" }
        ],
        password: [
          { message: "密码不能为空", trigger: "blur" },
          { validator: validatePassword, trigger: "blur" }
        ],
        idCardNumber: [
          { required: true, message: "身份证号码不能为空", trigger: "blur" },
          { validator: validateIdCardNumber, trigger: "blur" }
        ],
        userName: [
          { required: true, message: "真实姓名不能为空", trigger: "blur" },
          { validator: validateuserName, trigger: "blur" }
        ],
        companyName: [{ required: true, message: "单位名称不能为空", trigger: "blur" },{ validator: validatecompanyName, trigger: "blur" }]
      },
      staffNo: window.pageData.USER_MANAGEMENT.staffNo + "：",
    };
  },
  methods: {
    openDialogVisible(type, val) {
      this.disabled = type === "edit" ? true : false;
      this.title = "新增用户";
      if (type === "edit") {
        this.title = "修改用户";
        this.ruleForm.account = val.account;
        this.ruleForm.userName = val.userName;
        this.ruleForm.idCardNumber = val.idCardNumber;
        this.ruleForm.policeId = val.policeId;
        this.ruleForm.companyName = val.companyName;
        this.ruleForm.password = val.password;
        this.ruleForm.isKpi = val.isKpi;
      }
      this.userId = val ? val.id : "";
      this.dialogVisible = true;
    },
    closeDialog() {
      this.$emit("callBack");
      this.$refs["ruleForm"].resetFields();
      this.$refs["ruleForm"].clearValidate();
      this.dialogVisible = false;
    },
    msg(err) {
      this.$alert(err, "提示", {
        confirmButtonText: "确定",
        callback: action => {}
      });
    },
    save() {
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          if (this.disabled) {
            //修改用户
            this.updateUser();
          } else {
            this.addUser();
          }
        }
      });
    },
    //增加用户
    addUser() {
      this.loading = true;
      let datas = {
        search: this.ruleForm.idCardNumber,
        isLock: "",
        page: 1,
        per_page: 100,
        sort: "-id"
      };
      getUserList(datas)
        .then(res => {
          this.loading = false;
          if (res.data.success) {
            if (res.data.data.list.length == 0) {
              //向数据库添加用户
              addUserInfo(this.ruleForm).then(res => {
                if (res.data.success) {
                  this.$message.success("注册成功");
                  this.closeDialog();
                } else {
                  this.msg(res.data.message);
                  this.loading = false;
                }
              });
            } else {
              this.$message.error("已存在相同身份证号，请修改");
            }
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch(err => {
          this.loading = false;
        });
    },
    //修改用户
    updateUser() {
      let params = {
        account: this.ruleForm.account,
        userName: this.ruleForm.userName,
        idCardNumber: this.ruleForm.idCardNumber,
        policeId: this.ruleForm.policeId,
        companyName: this.ruleForm.companyName,
        isKpi: false
      };
      if (this.ruleForm.password) {
        params.password = this.ruleForm.password;
      }
      this.loading = true;
      updateUser(this.userId, params).then(res => {
        this.loading = false;
        if (res.data.success) {
          this.$message.success("修改成功");
          this.closeDialog();
        } else {
          this.msg(res.data.message);
        }
      });
    }
  }
};
</script>

